using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.OutboundManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.OutboundManagement;

namespace RBAC.Write.Api.Application.Handler.ERP.OutboundManagement
{
    public class DeleteSalesOutboundHandler : IRequestHandler<DeleteSalesOutboundCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<SalesOutbound> outboundRepo;
        private readonly IBaseRepository<SalesOutboundDetail> detailRepo;
        private readonly ILogger<DeleteSalesOutboundHandler> logger;

        public DeleteSalesOutboundHandler(
            IBaseRepository<SalesOutbound> outboundRepo,
            IBaseRepository<SalesOutboundDetail> detailRepo,
            ILogger<DeleteSalesOutboundHandler> logger)
        {
            this.outboundRepo = outboundRepo;
            this.detailRepo = detailRepo;
            this.logger = logger;
        }

        public Task<APIResult<bool>> Handle(DeleteSalesOutboundCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>();
            try
            {
                var header = outboundRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = false", new { Id = request.Id });
                if (header == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "单据不存在";
                    result.Data = false;
                    return Task.FromResult(result);
                }
                // 仅开立状态允许删除
                if (!string.Equals(header.OrderStatus, "开立", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "仅开立状态的销售出库单可删除";
                    result.Data = false;
                    return Task.FromResult(result);
                }

                var sql = @"START TRANSACTION;
UPDATE SalesOutbound SET IsDeleted = true WHERE Id = @Id AND IsDeleted = false;
UPDATE SalesOutboundDetail SET IsDeleted = true WHERE SalesOutboundId = @Id AND IsDeleted = false;
COMMIT;
SELECT 1;";

                try
                {
                    var ok = outboundRepo.QueryFirstOrDefault<int>(sql, new { Id = request.Id });
                    result.Code = APIEnums.Success;
                    result.Msg = "删除销售出库成功";
                    result.Data = ok == 1;
                }
                catch (Exception ex)
                {
                    outboundRepo.Execute("ROLLBACK;");
                    logger.LogError(ex, "删除销售出库失败: {Message}", ex.Message);
                    result.Code = APIEnums.Error;
                    result.Msg = "删除销售出库失败";
                    result.Data = false;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除销售出库异常: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "删除销售出库异常";
                result.Data = false;
            }

            return Task.FromResult(result);
        }
    }
}
